package com.baizhi.hospital.aspect;

import com.baizhi.hospital.annotation.LogAnnotation;
import com.baizhi.hospital.dao.HospLogDao;
import com.baizhi.hospital.entity.HospLog;
import com.baizhi.hospital.entity.Triage;
import com.baizhi.hospital.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.UUID;

@Configuration
@Aspect
public class LogAspect {
	@Resource
	private HospLogDao hospLogDao;


	@After("@annotation(com.baizhi.hospital.annotation.LogAnnotation)")
	public void logRecord(JoinPoint joinPoint) {
//		创建日志记录对象
		HospLog hospLog = new HospLog();


//		获取request对象，拿到session，获取登陆的时候的用户信息
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
//		真实姓名
		hospLog.setLogOprater(user.getRealName());
//		时间
		hospLog.setLogDate(LocalDateTime.now());
//		日志的时间
		hospLog.setLogId(UUID.randomUUID().toString().replace("-", ""));

//		获取被切入的方法上的注解
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//		获取请求的方法上面的指定的注解
		Method method = signature.getMethod();
		LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);

//		获取操作内容
		String value = annotation.value();
//		获取操作类型
		int type = annotation.type();
//		赋值
		hospLog.setLogContent(value);
		hospLog.setLogType(type);

//		获取方法的参数
		Triage triage = null;
		Object[] args = joinPoint.getArgs();
		String t = null;
		for (Object o : args) {
			if (o instanceof String) {
				t = (String) o;
			}
		}
		if (t != null) {
			hospLog.setLogContent(value + ":患者" + t);
		}

		hospLogDao.insertLog(hospLog);
	}
}
